/*
 * @Author: Yuluo 568055454@qq.com
 * @Date: 2023年06月23日 13:59:42
 * @LastEditors: Yuluo 568055454@qq.com
 * @LastEditTime: 2023年06月23日 14:14:58
 * @FilePath: \Mood-Blog-System\blog\src\utils\storage\cookie.ts
 * @Description: Cookie存储cookieStorage
 * Copyright (c) 2023 by Yuluo, All Rights Reserved. 
 */
/**
 * 设置Cookie
 * @param name Cookie名称
 * @param value Cookie值
 * @param days 过期天数 默认1天
 */
export function setCookie(name: string, value: string, days: number = 1): void {
    if (!name || !value) throw new Error('setCookie：name or value is null');
    const date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    const expires = "expires=" + date.toUTCString();
    document.cookie = name + "=" + value + ";" + expires + ";path=/";
}

/**
 * 获取Cookie值
 * @param name Cookie名称
 * @returns Cookie值
 */
export function getCookie(name: string): string | null {
    if (!name) throw new Error('getCookie：name is null');
    const cookieName = name + "=";
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
        let cookie = cookies[i];
        while (cookie.charAt(0) === ' ') {
            cookie = cookie.substring(1);
        }
        if (cookie.indexOf(cookieName) === 0) {
            return cookie.substring(cookieName.length, cookie.length);
        }
    }
    return null;
}

/**
 * 删除Cookie
 * @param name Cookie名称
 */
export function deleteCookie(name: string): void {
    if (!name) throw new Error('deleteCookie：name is null');
    setCookie(name, "", -1);
}
